#!/bin/ash -efu
#
# mki-copy-efiboot
#
# This file is part of mkimage
# Copyright (C) 2007-2009  Alexey Gladkov <gladkov.alexey@gmail.com>
# Copyright (C) 2012       Michael Shigorin <mike@altlinux.org>
#
# This file is covered by the GNU General Public License,
# which should be included with mkimage as the file COPYING.
#

. "${0%/*}"/mki-sh-functions

verbose "has started executing."

pkgs="${PACKAGES_REQUIRED_COPY_EFIBOOT:-}"

[ -d "$chroot" ] ||
	fatal "$dir: does not look like a hasher work directory."

# should be a package name
[ -n "${EFI_BOOTLOADER:-}" ] ||
	fatal "EFI_BOOTLOADER is empty."

pkgs="$pkgs $EFI_BOOTLOADER"

# should be a package name
[ -z "${EFI_SHELL:-}" ] ||
	pkgs="$pkgs $EFI_SHELL"

[ -z "${EFI_CERT:-}" ] ||
	pkgs="$pkgs alt-uefi-certs shim-signed shim-unsigned"

case "${EFI_BOOTLOADER:-}" in
refind)	# won't boot unsigned kernels in SB mode
	# elilo for x86_64 boot stack compatibility
	# grub-efi for ia32 EFI on x86_64
	pkgs="$pkgs elilo grub-efi"
	;;
grub-efi)
	pkgs="$pkgs grub-efi"
	;;
esac

[ -z "${EFI_MEMTEST86:-}" ] ||
	pkgs="$pkgs $EFI_MEMTEST86"

mki-install $pkgs ||
	fatal "failed to install packages: $pkgs."

cp $verbose -f -- "$bindir/mki-copy-efiboot-chrooted" "$chroot/.host/efiboot-chrooted"

make_exec "$chroot/.host/efiboot.sh" <<EOF
#!/bin/sh -efu${verbose:+x}

verbose="$verbose"
EFI_CERT="${EFI_CERT-}"
EFI_BOOTLOADER="${EFI_BOOTLOADER-}"
EFI_BOOTARGS="${EFI_BOOTARGS-}"
EFI_FILES_COPY="${EFI_FILES_COPY-}"
EFI_FILES_REPLACE="${EFI_FILES_REPLACE-}"

. /.host/efiboot-chrooted
EOF

rc=0
mki-run "/.host/efiboot.sh" || rc=$?
rm -f -- "$chroot/.host/efiboot.sh"
find "$chroot/.in" -mindepth 1 -maxdepth 1 -exec rm -rf -- '{}' '+'
exit $rc
